﻿using Plane;
using Plane.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Media;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Rebar;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
namespace Plane
{
    public partial class GameForm : Form
    {
        private const int PLANE_OFFSET = 2;
        private int pix_x = 0;
        private int pix_y = 0;
        int shot_y = 0;
        private int blood_x = 0;
        private int blood_y = -100;
        private static Random rand = new Random();
        private Image[] bgrounds;
        int index = 0;
        Image avatar = Resources.imgHeadSheep;
        Image boomImg = Resources.bomb4;
        Image shotImg = Resources.shotgun;
        Image bloodImg = Resources.bloodbox;

        public static bool isDropGun = false;
        
        public static bool isBloodDropping = false;  // 当前是否有血包在下落

        private GameChoosing gamechoosing;
        private MainWindow mainwindow;
        private string currentUsername;
        public GameForm(GameChoosing gamechoosing, MainWindow mainwindow)
        {
            InitializeComponent();
            this.Size = new Size(420, 630);
            this.DoubleBuffered = true;
            this.KeyPreview = true;

            // 初始化定时器
            timer1 = new System.Windows.Forms.Timer();
            timer1.Interval = 100; 
            timer1.Tick += new EventHandler(timer1_Tick);
            timer1.Start();

            timer2 = new System.Windows.Forms.Timer();
            timer2.Interval = 100;
            timer2.Tick += new EventHandler(timer2_Tick);
            timer2.Start();

            // 关联事件
            this.Load += new EventHandler(GameForm_Load);
            this.KeyDown += new KeyEventHandler(GameForm_KeyDown);
            this.KeyUp += new KeyEventHandler(GameForm_KeyUp);

            this.KeyDown += GameForm_KeyDown;
            this.KeyUp += GameForm_KeyUp;
            this.mainwindow = mainwindow;
            //初始化
            
            this.Focus();
        }
        public GameForm(GameChoosing gamechoosing, MainWindow mainwindow,string username )
        {
            InitializeComponent();
            this.Size = new Size(420, 630);
            this.DoubleBuffered = true;
            this.KeyPreview = true;
            
            this.currentUsername = username;
            //MessageBox.Show(currentUsername);
            // 初始化定时器
            timer1 = new System.Windows.Forms.Timer();
            timer1.Interval = 100;
            timer1.Tick += new EventHandler(timer1_Tick);
            timer1.Start();

            timer2 = new System.Windows.Forms.Timer();
            timer2.Interval = 100;
            timer2.Tick += new EventHandler(timer2_Tick);
            timer2.Start();

            // 关联事件
            this.Load += new EventHandler(GameForm_Load);
            this.KeyDown += new KeyEventHandler(GameForm_KeyDown);
            this.KeyUp += new KeyEventHandler(GameForm_KeyUp);

            this.KeyDown += GameForm_KeyDown;
            this.KeyUp += GameForm_KeyUp;
            this.mainwindow = mainwindow;


            var userInfo = UserDbHelper.GetUserInformationByUsername(currentUsername);
            MyPlane.bloodRecovery = userInfo.RecoveryAmount;
            MyPlane.isGetGun = userInfo.BulletAmount;

            this.Focus();
        }
        private void GameForm_Load(object sender, EventArgs e)
        {
            InitBackground();
            this.Focus();
        }

        public void InitBackground()
        {
            bgrounds = new Image[4];
            Random rd = new Random();
            index = rd.Next(0, 4);

            bgrounds[0] = Resources.background1;
            bgrounds[1] = Resources.background2;
            bgrounds[2] = Resources.background3;
            bgrounds[3] = Resources.background4;
        }

        public void BackMove(Graphics e)
        {
            pix_y += PLANE_OFFSET;
            if (pix_y > 630)
            {
                pix_y = 0;
            }
        }

        public void ProduceShotGun()
        {
            Rectangle sgRect = new Rectangle(new Random().Next(0, 350), shot_y, shotImg.Width, shotImg.Height);
            Rectangle mpRect = new Rectangle(MyPlane.x, MyPlane.y, MyPlane.myPlaneImg.Width, MyPlane.myPlaneImg.Height);


            if (new Random().Next(0, 100) == 2)
            {
                isDropGun = true;
            }
            if (isDropGun &&  sgRect.IntersectsWith(mpRect))
            {
                MyPlane.isGetGun +=1;
                shot_y = -100;
            }
            shot_y += 5;
            if (shot_y > 950)
            {
                shot_y = -100;
            }
        }

        public void ProduceBlood()
        {
            // 没有血包在下落则有概率生成一个新的
            if (!isBloodDropping && rand.Next(0, 100) == 1)
            {
                isBloodDropping = true;
                blood_x = rand.Next(0, 390);
                blood_y = 0;
            }

            if (isBloodDropping)
            {
                Rectangle mpRect = new Rectangle(MyPlane.x, MyPlane.y, MyPlane.myPlaneImg.Width, MyPlane.myPlaneImg.Height);
                Rectangle bbRect = new Rectangle(blood_x, blood_y, bloodImg.Width, bloodImg.Height);

                blood_y += 5;

                if (bbRect.IntersectsWith(mpRect))
                {
                    MyPlane.isBloodCollected = true;    // 表示已经捡到
                    isBloodDropping = false;
                    blood_y = -100;
                }

                if (blood_y > 950) // 超出屏幕底部
                {
                    isBloodDropping = false;
                    blood_y = -100;
                }
            }
        }


        private void DrawGame(Graphics g)
        {
            this.BackMove(g);
            var userInfo = UserDbHelper.GetUserInformationByUsername(currentUsername);
            //MessageBox.Show(currentUsername);
            if (!string.IsNullOrEmpty(userInfo.Password))
            {
                
                if (bgrounds != null && index >= 0 && index < bgrounds.Length)
                {
                    g.DrawImage(bgrounds[index], pix_x, pix_y, 420, 630);
                    g.DrawImage(bgrounds[index], pix_x, pix_y - 630, 420, 630);
                }

                //g.DrawImage(avatar, 10, 10);
                g.DrawRectangle(new Pen(Color.Black), new Rectangle(10, 100, 100, 10));
                g.FillRectangle(Brushes.Red, 10, 101, MyPlane.health, 9);

                g.DrawRectangle(new Pen(Color.Blue), new Rectangle(10, 120, 100, 10));
                g.FillRectangle(Brushes.Green, 11, 121, MyPlane.score, 9);
                g.DrawString("Player："+currentUsername, new Font("宋体", 9, FontStyle.Bold), Brushes.Yellow, new Point(10, 140));
                g.DrawString("Score：" + MyPlane.score, new Font("宋体", 9, FontStyle.Bold), Brushes.Yellow, new Point(10, 160));

                MyPlane.MyPlaneShow(g);
                MyPlane.MyPlaneMove();

                MyBullet.ProduceMybul();
                MyBullet.MoveMybul(g);
                MyBullet.IsHitEnemy(g);

                Fighter.ProduceFighter();
                Fighter.FighterMove(g);

                EnemyBullet.ProduceEnbul();
                EnemyBullet.MoveEnbul(g);
                EnemyBullet.HitPlane(g);

                this.ProduceShotGun();
                this.ProduceBlood();

                if (isDropGun && MyPlane.isGetGun <2 )
                {
                    g.DrawImage(shotImg, 200, shot_y);
                }
                if (MyPlane.isGetGun >= 2)
                {
                    g.DrawImage(shotImg, new Point(0, -500));
                }

                if (isBloodDropping)
                {
                    g.DrawImage(bloodImg, blood_x, blood_y);
                }
                
            }
           
            
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            Bitmap bufferBmp = new Bitmap(this.ClientRectangle.Width - 1, this.ClientRectangle.Height - 1);
            Graphics g = Graphics.FromImage((System.Drawing.Image)bufferBmp);
            this.DrawGame(g);

            e.Graphics.DrawImage(bufferBmp, 0, 0);
            g.Dispose();
            base.OnPaint(e);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.Invalidate();
        }

        private void GameForm_KeyDown(object sender, KeyEventArgs e)
        {
            MyPlane.Keydown(e.KeyCode);
        }

        private void GameForm_KeyUp(object sender, KeyEventArgs e)
        {
            MyPlane.Keyup(e.KeyCode);
           MyPlane.myPlaneImg =MyPlane.myPlaneImgS;
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            Graphics g = this.CreateGraphics();
            for (int j = 0; j < Fighter.fighters.Count; j++)
            {
                if (Fighter.fighters[j].flag)
                {
                    g.DrawImage(boomImg, Fighter.fighters[j].GetLoc());
                    SoundPlayer music = new SoundPlayer(Resources.BOMB21);
                    music.Play();
                    Fighter.fighters.Remove(Fighter.fighters[j]);
                }
            }
        }

        private void roundButton1_Click(object sender, EventArgs e)
        {
            UpdateUserInfo();

            // 解绑事件
            timer1.Tick -= timer1_Tick;
            timer2.Tick -= timer2_Tick;

            // 停止定时器，防止在销毁后继续触发事件
            timer1.Stop();
            timer2.Stop();

            

            // 关闭旧主窗口
            mainwindow.Close();

            // 创建并显示新的 MainWindow
            MainWindow newmainwindow = new MainWindow(currentUsername);
            newmainwindow.Show();
            MyPlane.Reset();
            EnemyBullet.Reset();
            Fighter.Reset();
            MyBullet.reset();
            // 最后关闭旧 GameForm
            this.Close();
        }
        private void UpdateUserInfo()
        {

            var userInfo = UserDbHelper.GetUserInformationByUsername(currentUsername);
            //MessageBox.Show(currentUsername);
            if (!string.IsNullOrEmpty(userInfo.Password))
            {
                // 用户信息存在
                string password = userInfo.Password;
                int money = userInfo.Money;
                int highestScore = userInfo.HighestScore;
                int recoveryAmount = userInfo.RecoveryAmount;

                // 进行更新
                int currentScore = MyPlane.score;
                if (MyPlane.isGameOver)
                {
                    money += 5000;
                    money += currentScore * 100;
                }
                MyPlane.isGameOver=false;
                MyPlane.usedBlood= false;
                int newHighestScore= (currentScore> highestScore) ? currentScore : highestScore;
                UserDbHelper.UpdateMoney(currentUsername, money);
                UserDbHelper.UpdateHighestScore(currentUsername, newHighestScore);
            }
            

        }


    }
}